var async = require("async")
//大字版翻牌机
module.exports.createRoom = function(roomId,channelService,GameRemote) {
	console.log("new!!55555创建房间:"+roomId)
	var gameBasic = require("./basic/gameBasic.js")
	var logicBasic = require("./logic/flopMachineLogic.js")
	var logic = new logicBasic()
	var local = {}
	var playerNum = 1
	var room = new gameBasic(roomId,"flopMachine",playerNum,channelService,GameRemote)
	room.inventory = 1000 		//总库存
	room.singleInventory = 0 	//个人库存
	room.contorl = 0 			//控制概率
	logic.shuffle()
	var state = 0     	   		//0  空闲   1  换牌阶段   2  取分或比大小阶段
	var basicScore = 100   		//底分
	var betScore = 0 	   		//下注分值
	var allScore = 0 			//总下注分数(包含比大小)
	var winScore = 0 	   		//当前赢取
	var diceCount = 0 	   		//比大小次数
	var gameType = 0 	   		//游戏类型
	var level = 0 	   	   		//场次级别
	var table = 0 		   		//桌子号
	var countdownTime = false 	//结算倒计时
	var curInfo = {}
	room.lock = false  			//状态锁
	var scoreType = 102 		//货币类型
	//主循环
	room.mainUpdate = function(dt) {
		if(countdownTime !== false){
			countdownTime -= dt
			if(countdownTime < 0){
				countdownTime = false
				room.coerceOver()
			}
		}
	}
	//更新库存
	room.updateInventory = function(value) {
		async.waterfall([
			function(next) {
				GameRemote.dbService.db.hincrby("game:gold:inventory:"+gameType,level,value,function(err,data) {
					next()
				})
			},
			function(next) {
				if(room.singleInventory == 0){
					next()
				}else{
					GameRemote.dbService.db.hincrby("game:singleInventory",room.players[0].uid,value,function(err,data) {
						//第一次变界后删除库存
						data = parseInt(data)
						if((data - value) * data <= 0){
							console.log("边界清库存 最终值 : 改变值",data,value)
							GameRemote.dbService.db.hdel("game:singleInventory",room.players[0].uid,function(err,data) {
								next()
							})
						}else{
							next()
						}
					})
				}
			},
			function() {
				room.acquireInventory()
			}
		],
		function(err) {
			console.log(err)
		})
	}
	//获取最新库存
	room.acquireInventory = function() {
		if(level != "free"){
			async.waterfall([
				function(next) {
					//获取总库存
					GameRemote.dbService.db.hget("game:gold:inventory:"+gameType,level,function(err,data) {
						console.log("game:gold:inventory : ",data)
						room.inventory = parseInt(data) || 0
						next()
					})
				},
				function(next) {
					//获取个人库存
					GameRemote.dbService.db.hget("game:singleInventory",room.players[0].uid,function(err,data) {
						console.log("singleInventory : ",data)
						if(data && data != 0){
							room.singleInventory = parseInt(data)
						}else{
							room.singleInventory = 0
						}
						next()
					})
				},
				function() {
					room.checkInventory()
				}
			],function(err) {
				console.log(err)
			})
		}else{
			room.contorl = 0.2
		}
	}
	//检查库存   库存小于0时降低玩家好运值
	room.checkInventory = function() {
		if(!room.singleInventory || room.singleInventory == 0){
			if(room.inventory <= 0){
				console.log("库存低 : ",room.inventory)
				room.contorl = -1
			}else{
				room.contorl = parseInt(room.players[0].playerInfo.contorl) || -0.2
				console.log("库存高 : ",room.inventory,room.players[0].playerInfo.contorl,room.contorl)
			}
		}else{
			//个人库存优先
			if(room.singleInventory > 0){
				room.contorl = 0.35
			}else{
				room.contorl = -1
			}
		}
		console.log("control : ",room.contorl)
	}
	room.setBeforeInfo = function(info) {
		if(info.basicScore){
			basicScore = info.basicScore
		}
		if(info.gameType){
			gameType = info.gameType
		}
		if(info.level){
			level = info.level
		}
		if(info.table){
			table = info.table
		}
		if(level == "free"){
			scoreType = 105
		}
		room.acquireInventory()
	}
	//单局结束
	local.gameEnd = function() {
		console.log("winScore : ",winScore,allScore - winScore)
		//保存本局记录
		curInfo.time = (new Date()).getTime()
		curInfo.allScore = allScore
		GameRemote.dbService.db.rpush("game:flopMachine:history:"+gameType+""+level+":"+table,JSON.stringify(curInfo),function(err,data) {
			if(!err && data > 100){
				GameRemote.dbService.db.ltrim("game:flopMachine:history:"+gameType+""+level+":"+table,-100,-1)
			}
		})
		//更新库存
		if(scoreType == 102){
			room.updateInventory(allScore - winScore)
		}
		//大牌型处理
		if(curInfo.result && curInfo.result.type >= 8){
			console.log("更新出奖记录 : ",curInfo.result.type)
			GameRemote.dbService.db.hincrby("game:flopMachine:record:"+gameType+""+level+":"+table,curInfo.result.type,1,function(err,data) {})
			var userRecord = {
				handCards : curInfo.secondCard,
				result : curInfo.result,
				bet : curInfo.bet,
				time : curInfo.time,
				gameType : gameType,
				level : level,
				table : table
			}
			//更新个人记录
			GameRemote.dbService.db.rpush("game:user:history:"+gameType+":"+room.players[0].uid,JSON.stringify(userRecord),function(err,data) {
				if(!err && data > 10){
					GameRemote.dbService.db.ltrim("game:user:history:"+gameType+""+room.players[0].uid,-10,-1)
				}
			})
			//更新排行榜记录
			var record = {
				level : level,
				table : table,
				handCards : curInfo.secondCard,
				result : curInfo.result,
				bet : curInfo.bet,
				uid : room.players[0].uid,
				nickname : room.players[0].playerInfo.nickname,
				head : room.players[0].playerInfo.head
			}
			GameRemote.dbService.db.rpush("game:ranking:record:"+gameType,JSON.stringify(record),function(err,data) {
				if(!err && data > 100){
					GameRemote.dbService.db.ltrim("game:ranking:record:"+room.players[0].uid,-100,-1)
				}
			})
			//跑马灯通知
			var rollingInfo = {
				"type" : "awardRolling",
				"gameType" : gameType,
				"level" : level,
				"table" : table,
				"curType" : curInfo.result.type,
				"nickname" : room.players[0].playerInfo.nickname,
				"winScore" : curInfo.winScore,
				"bombAward" : curInfo.bombAward,
				"passAward" : curInfo.passAward
			}
			GameRemote.app.rpc.game.remote.broadcast(null,rollingInfo,null)
			//体验场赠送钻石
			if(level == "free"){
				var awardItem = 101
				var awardValue = 5
				GameRemote.app.rpc.db.remote.addItemReason(null,room.players[0].uid,awardItem,awardValue,"牌型奖励:"+curInfo.result.type,function(data) {
					var info = {
						cmd : "cardTypeAward",
						awardItem : awardItem,
						awardValue : awardValue,
						result : curInfo.result
					}
					room.sendAll(info)
				})
			}
		}
		//后台记录
		curInfo.gameType = gameType
		curInfo.level = level
		curInfo.table = table
	    var messageInfo = {
	      messageType : "historyRecord",
	      data : curInfo
	    }
	    GameRemote.app.rpc.db.cacheMessage.writeMessage(null,JSON.stringify(messageInfo),null)
		var notify = {
			cmd : "gameEnd"
		}
		room.sendAll(notify)
		state = 0
		winScore = 0
		diceCount = 0
		betScore = 0
		allScore = 0
		logic.handCards = []
	}
	//开始发牌
	room.handle.sendCard = function(uid,sid,param,cb) {
		if(state !== 0){
			cb(false,"不在空闲阶段")
			return
		}
		if(room.lock){
			cb(false,"请勿重复操作")
			return
		}
		room.lock = true
		var power = param.power
		if(typeof(power) != "number" || power < 1 || power > 5){
			power = 1
		}else{
			power = parseInt(power)
		}
		betScore = power * basicScore
		allScore = betScore
		curInfo = {}
		async.waterfall([
				function(next) {
					//检测金币
					GameRemote.dbService.getItem(uid,scoreType,function(data) {
						if(data < betScore){
							room.lock = false
							cb(false,"金币不足")
							return
						}
						next()
					})
				},
				function(next) {
					//扣除金币
					GameRemote.app.rpc.db.remote.addItemReason(null,uid,scoreType,-betScore,"开始游戏:"+level+":"+table,function(flag,data) {
						curInfo.curScore = data
						next()
					})
				},
				function(next) {
					//开始发牌
					state = 1
					winScore = 0
					diceCount = 0
					curInfo.dicingList = []
					curInfo.uid = uid
					curInfo.winScore = 0
					var tmpInventory = false
					if(!room.singleInventory && room.inventory){
						tmpInventory = room.inventory
					}
					logic.sendCard(room.contorl,tmpInventory,betScore,0)
					curInfo.bet = betScore
					curInfo.firstCard = room.getCardList(logic.handCards)
					var info = {
						handCards : room.getCardList(logic.handCards),
						result : logic.getCardType(logic.handCards),
						holdCards : logic.holdCards(logic.handCards)
					}
					info.holdCardsType = logic.holdCardsType(info.holdCards)
					cb(true,info)
					room.lock = false
				}
			],function(err) {
				room.lock = false
				console.log(err)
		})
	}
	//换牌
	room.handle.changeCards = function(uid,sid,param,cb) {
		if(state !== 1){
			cb(false,"不在换牌阶段")
			return
		}
		var indexs = param.indexs
		//参数校验
		if(!indexs || typeof(indexs) != "object" || indexs.length == undefined || indexs.length > 5 || indexs.length < 0){
			console.log("indexs",indexs)
			cb(false,"indexs参数错误")
			return
		}
		for(var i = 0;i < indexs.length - 1;i++){
			if(!logic.handCards[indexs[i]]){
				console.log("indexs",indexs)
				cb(false,"indexs参数错误")
				return
			}
			for(var j = i + 1;j < indexs.length;j++){
				if(indexs[i] == indexs[j]){
					console.log("indexs",indexs)
					cb(false,"indexs参数错误")
					return
				}
			}
		}
		logic.changeCards(indexs,room.contorl,0)
		curInfo.changeIndexs = indexs
		curInfo.secondCard = room.getCardList(logic.handCards)
		var result = logic.getCardType(logic.handCards)
		curInfo.result = result
		var info = {
			indexs : indexs,
			handCards : room.getCardList(logic.handCards),
			result : result
		}
		cb(true,info)
		if(result.price){
			//获胜进入比大小
			state = 2
			winScore = result.price * betScore
		}else{
			//失败则进入空闲
			local.gameEnd()
		}
	}
	//检测牌型
	room.handle.checkCardType = function(uid,sid,param,cb) {
		var handCards = param.handCards
		var result = logic.getCardType(handCards)
		cb(true,result)
	}
	//取分
	room.handle.takeScore = function(uid,sid,param,cb) {
		if(state !== 2){
			cb(false,"不在取分阶段")
			return
		}
		if(!winScore){
			console.log("winScore error : ",winScore)
			cb(false)
			return
		}
		if(room.lock){
			cb(false,"请勿重复操作")
			return
		}
		room.lock = true
		var tmpAllScore = 0
		curInfo.winScore = winScore
		tmpAllScore += curInfo.winScore
		//增加金币
		var info = {
			winScore : winScore
		}
		if(gameType == "hqlMachine"){
			//爆机奖励
			if(diceCount > 0 && winScore >= 200 * basicScore){
				curInfo.bombAward = 50 * basicScore
				tmpAllScore += curInfo.bombAward
				info.bombAward = curInfo.bombAward
			}
			//过关彩金
			if(diceCount > 0 && winScore >= 75 * basicScore){
				curInfo.passAward = 4 * basicScore * diceCount
				tmpAllScore += curInfo.passAward
				info.passAward = curInfo.passAward
			}
		}
		GameRemote.app.rpc.db.remote.addItemReason(null,uid,scoreType,tmpAllScore,"取分",function(flag,data) {
			room.lock = false
			info.curScore = data
			curInfo.curScore = data
			cb(true,info)
			local.gameEnd()
		})
	}
	//比大小
	room.handle.dicing = function(uid,sid,param,cb) {
		if(state !== 2){
			cb(false,"不在取分阶段")
			return
		}
		if(diceCount >= 7){
			cb(false,"最大不能超过七次")
			return
		}
		if(room.lock){
			cb(false,"请勿重复操作")
			return
		}
		room.lock = true
		var rateType = param.rateType
		var bigFlag = param.bigFlag
		switch(rateType){
			case "half":
				//半比
				GameRemote.app.rpc.db.remote.addItemReason(null,uid,scoreType,parseInt(winScore * 0.5),"半比返回",function(flag,data) {
					room.lock = false
					winScore *= 0.5
					allScore -= winScore
					local.dicingEnd(bigFlag,rateType,cb)
				})
			break
			case "same":
				//比倍
				local.dicingEnd(bigFlag,rateType,cb)
				room.lock = false
			break
			case "twice":
				//双比
				GameRemote.dbService.getItem(uid,scoreType,function(data) {
					if(data < winScore){
						room.lock = false
						cb(false,"金币不足")
						return
					}
					GameRemote.app.rpc.db.remote.addItemReason(null,uid,scoreType,-winScore,"双比消耗",function(flag,data) {
						room.lock = false
						allScore += winScore
						winScore *= 2
						local.dicingEnd(bigFlag,rateType,cb)
					})
				})
			break
			default:
				room.lock = false
				cb(false,"参数错误")
		}
	}
	local.dicingEnd = function(bigFlag,rateType,cb) {
		diceCount++
		if(bigFlag == true){
			bigFlag = true
		}else{
			bigFlag = false
		}
		var rand = Math.random()
		var card = {}
		var score = winScore
		var loseFlag = false
		var winFlag = false
		if(rand < 0.5){
			winFlag = true
			if(room.singleInventory == 0){
				if(room.inventory < winScore * 2){
					winFlag = false
				}
			}else{
				if(room.singleInventory < winScore * 2){
					winFlag = false
				}
			}
		}
		if(winFlag){
		// if(bigFlag){
			//赢
			if(bigFlag){
				//开大
				card.num = Math.floor(Math.random() * 6) + 8
				card.type = Math.floor(Math.random() * 4)

			}else{
				//开小
				card.num = Math.floor(Math.random() * 6) + 1
				card.type = Math.floor(Math.random() * 4)
			}
			if(rand < 0.05){
				card.num = 14
				card.type =  Math.floor(Math.random() * 2)
			}
			winScore *= 2
		}else{
			loseFlag = true
			//输
			if(bigFlag){
				//开小
				card.num = Math.floor(Math.random() * 6) + 1
				card.type = Math.floor(Math.random() * 4)
			}else{
				//开大
				card.num = Math.floor(Math.random() * 6) + 8
				card.type = Math.floor(Math.random() * 4)
			}
			winScore = 0
		}
		GameRemote.dbService.db.rpush("game:flopMachine:dicingHistory:"+gameType+""+level+":"+table,JSON.stringify(card),function(err,data) {
			if(!err && data > 10){
				GameRemote.dbService.db.ltrim("game:flopMachine:dicingHistory:"+gameType+""+level+":"+table,-10,-1)
			}
		})
		var info = {
			card : card,
			bigFlag : bigFlag,
			score : score,
			winScore : winScore,
			rateType : rateType
		}
		curInfo.dicingList.push(info)
		cb(true,info)
		if(loseFlag){
			local.gameEnd()
		}
	}
	//查询历史记录
	room.handle.getHistory = function(uid,sid,param,cb) {
		GameRemote.dbService.db.lrange("game:flopMachine:history:"+gameType+""+level+":"+table,-10,-1,function(err,data) {
			if(!err && data){
				cb(true,data)
			}else{
				cb(true,[])
			}
		})
	}
	//获取比牌记录
	room.handle.getDicingHistory = function(uid,sid,param,cb) {
		GameRemote.dbService.db.lrange("game:flopMachine:dicingHistory:"+gameType+""+level+":"+table,-6,-1,function(err,data) {
			if(!err && data){
				cb(true,data)
			}else{
				cb(true,[])
			}
		})
	}
	//获取出奖记录
	room.handle.getRecordHistory = function(uid,sid,param,cb) {
		GameRemote.dbService.db.hgetall("game:flopMachine:record:"+gameType+""+level+":"+table,function(err,data) {
			if(!err && data){
				cb(true,data)
			}else{
				cb(true,{})
			}
		})
	}
	//获取当前房间信息
	room.handle.getRoomInfo = function(uid,sid,param,cb) {
		var info = {
			state : state,
			basicScore : basicScore,
			betScore : betScore,
			winScore : winScore,
			diceCount : diceCount,
			roomType : room.roomType,
			gameType : gameType,
			level : level,
			table : table,
			handCards : room.getCardList(logic.handCards),
			result : logic.getCardType(logic.handCards),
			holdCards : curInfo.changeIndexs || logic.holdCards(logic.handCards),
			scoreType : scoreType
		}
		cb(true,info)
	}
	//强制结算
	room.coerceOver = function() {
		switch(state){
			case 1 :
				//换牌阶段根据牌型直接获取结果
				room.lock = true
				var result = logic.getCardType(logic.handCards)
				winScore = result.price * betScore
				curInfo.changeIndexs = [0,1,2,3,4]
				curInfo.secondCard = room.getCardList(logic.handCards)
				curInfo.winScore = winScore
				curInfo.result = result
				GameRemote.app.rpc.db.remote.addItemReason(null,room.players[0].uid,scoreType,winScore,"取分",function(flag,data) {
					local.gameEnd()
					room.gameOver()
					room.lock = false
				})
			break
			case 2 :
				//比大小阶段直接取分
				room.lock = true
				curInfo.winScore = winScore
				GameRemote.app.rpc.db.remote.addItemReason(null,room.players[0].uid,scoreType,winScore,"取分",function(flag,data) {
					local.gameEnd()
					room.gameOver()
					room.lock = false
				})
			break
		}
	}
	//获取手牌下标列表，用于存储
	room.getCardList = function(handCards) {
		var list = []
		for(var i = 0;i < handCards.length;i++){
			list.push(handCards[i].index)
		}
		return list
	}
	//玩家掉线
	room.disconnectFun = function(uid) {
		console.log("disconnectFun!!!")
		//空闲时掉线解散房间
		if(state == 0){
			room.userQuit(uid)
		}else{
			countdownTime = 3 * 60 * 1000
		}
	}
	//玩家重连
	room.reconnectionFun = function(uid) {
		countdownTime = false
		console.log("reconnectionFun!!!")
	}
	room.resetLogic = function(str) {
		logicBasic = require(str)
		logic = new logicBasic()
		logic.shuffle()
	}
	return room
}